package cn.mifengkong.appcommon.buriedpoint;

import android.text.TextUtils;

import com.mifengkong.frtools.util.FRDeviceUtil;
import com.mifengkong.frtools.util.FREncryptUtil;
import com.mifengkong.frtools.util.FRLog;
import com.mifengkong.frtools.util.FRSharedPreferences;
import com.mifengkong.frtools.util.NetWorkUtil;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by jiangyongxing on 2017/10/23.
 * 描述：
 */

public class YingyongbaoBuriedUtil {

    private static YingyongbaoBuriedUtil instance;

    private FormBody.Builder formBodyBuilder;
    private OkHttpClient mOkHttpClient;
    private IYingYongBaoBuriedHelper yingYongBaoBuriedHelper;
    private String mApplicationId = null;

    private YingyongbaoBuriedUtil(IYingYongBaoBuriedHelper yingYongBaoBuriedHelper) {
        if (null == yingYongBaoBuriedHelper || TextUtils.isEmpty(yingYongBaoBuriedHelper.getApplicationId())) {
            throw new IllegalArgumentException("YingyongbaoBuriedUtil 传入的参数有问题");
        }
        this.yingYongBaoBuriedHelper = yingYongBaoBuriedHelper;
        mApplicationId = yingYongBaoBuriedHelper.getApplicationId();
        init();
    }

    public static YingyongbaoBuriedUtil getInstance(IYingYongBaoBuriedHelper yingYongBaoBuriedHelper) {
        if (instance == null)
            instance = new YingyongbaoBuriedUtil(yingYongBaoBuriedHelper);
        return instance;
    }

    private static YingyongbaoBuriedUtil getInstance() {
        return instance;
    }


    private void init() {
        if (YingyongbaoAppidAndKeyList.needRequestQQBycurrentChannelId(mApplicationId) && !TextUtils.isEmpty(YingyongbaoAppidAndKeyList.getAppid(mApplicationId))) {//
            String phoneInfo = FRDeviceUtil.getPhoneInfo();
            if (!TextUtils.isEmpty(phoneInfo)) {
                StringBuilder sb = new StringBuilder();
                sb.append("app_type");
                sb.append("=");
                sb.append("ANDROID");
                sb.append("&");
                sb.append("click_id");
                sb.append("=");
                sb.append("");
                sb.append("&");
                sb.append("client_ip");
                sb.append("=");
                sb.append(NetWorkUtil.getHostIP());
                sb.append("&");
                sb.append("conv_time");
                sb.append("=");
                sb.append(String.valueOf(System.currentTimeMillis() / 1000));
                sb.append("&");
                sb.append("muid");
                sb.append("=");
                sb.append(FREncryptUtil.string2MD5(phoneInfo.toLowerCase()));
                sb.append("&");
                sb.append("sign_key");
                sb.append("=");
                sb.append(YingyongbaoAppidAndKeyList.getSignKey(mApplicationId));

                mOkHttpClient = new OkHttpClient();
                formBodyBuilder = new FormBody.Builder()
                        .add("click_id", "")
                        .add("muid", FREncryptUtil.string2MD5(phoneInfo.toLowerCase()))
                        .add("appid", YingyongbaoAppidAndKeyList.getAppid(mApplicationId))
                        .add("conv_time", String.valueOf(System.currentTimeMillis() / 1000))
                        .add("client_ip", TextUtils.isEmpty(NetWorkUtil.getHostIP()) ? "" : NetWorkUtil.getHostIP())//这个有可能是获取不到的，所以要做一下处理
                        .add("encstr", FREncryptUtil.string2MD5(sb.toString().trim()))
                        .add("encver", "1.0")
                        .add("advertiser_id", YingyongbaoAppidAndKeyList.getAdvertiserId(mApplicationId))
                        .add("app_type", "ANDROID");
            } else {
                yingYongBaoBuriedHelper.obtaineviceInformationFailed();
            }
        }
    }

    /**
     * 激活
     */
    public void activate() {
        if (getInstance().formBodyBuilder != null) {//这里只做了激活的判断，其他的判断（比如注册）不好再客户端判断
            if (TextUtils.isEmpty(FRSharedPreferences.getStringNotClear("MOBILEAPP_ACTIVITE", ""))) {
                requestServer("MOBILEAPP_ACTIVITE");
                FRSharedPreferences.setStringNotClear("MOBILEAPP_ACTIVITE", "MOBILEAPP_ACTIVITE");
            }

        }
    }

    /**
     * 注册
     */
    public void rigister() {
        if (getInstance().formBodyBuilder != null) {
            requestServer("MOBILEAPP_REGISTER");
        }
    }

    /**
     * 成单
     */
    public void createOrder() {
        if (getInstance().formBodyBuilder != null) {
            requestServer("MOBILEAPP_COST");
        }
    }

    void requestServer(String conv_type) {
        FormBody formBody = formBodyBuilder.add("conv_type", conv_type)
                .build();
        Request request = new Request.Builder()
                .url(TextUtils.concat("https://t.gdt.qq.com/conv/app/", YingyongbaoAppidAndKeyList.getAppid(mApplicationId), "/conv").toString())
                .post(formBody)
                .build();
        getInstance().mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                FRLog.e("jiang", "response-----" + response.body().string());
            }
        });
    }
}
